package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.exception.VerifyPriceException;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.ware.OrderTo;
import com.atguigu.common.utils.Constant;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.atguigu.gulimall.order.vo.pay.PayVO;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 订单确认页返回需要的数据
     * @return
     */

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        System.out.println("主线程...."+Thread.currentThread().getId());
        //ThreadLocal共享requestAttributes请求数据,从主线程拿出线程上下文数据共享到副线程
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //1.远程查询所有的收货地址列表
            System.out.println("getAddressFuture线程...."+Thread.currentThread().getId());
            //ThreadLocal共享requestAttributes请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressTo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);

        }, executor);
        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //2.远程查询购物车所有选中的购物项
            System.out.println("cartFuture线程...."+Thread.currentThread().getId());
            //ThreadLocal共享requestAttributes请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(cartItems);
            //feign在远程调用之前要构造请求,调用很多的拦截器,feign远程调用会丢失请求头
            //RequestInterceptor interceptor : requestInterceptors
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIds = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            List<SkuHasStockVo> hasStock = wareFeignService.getSkusHasStock(skuIds);
            if(hasStock!=null){
                Map<Long, Boolean> map = hasStock.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        },executor);

        //3.查询用户积分
        confirmVo.setIntegration(memberRespVo.getIntegration());
        //4.其他数据【分界线】

        //TODO 5.防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        CompletableFuture.allOf(getAddressFuture,cartFuture).get();
        return confirmVo;
    }

    /**
     * 订单确认页-提交订单
     * @return
     */
    @Override
    @Transactional
    //@GlobalTransactional 不适合高并发场景
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        System.out.println("OrderSubmitVo:"+vo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        confirmVoThreadLocal.set(vo);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //使用lua脚本完成原子性操作
        String script = OrderConstant.REDIS_SCRIPT;
        //1 验证令牌
        String orderToken = vo.getOrderToken();

        Long result= redisTemplate.execute(new DefaultRedisScript<>(script,Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId()),orderToken);
        if(result==0L){
            responseVo.setCode(1);
            return responseVo;
        }else {

            //验证成功-创建订单,验令牌,验价格,锁库存

            //1创建订单,订单项等信息
            OrderCreateTo order=createOrder();
            //验价
            BigDecimal payAmount = order.getOrderEntity().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            System.out.println("payAmount:"+payAmount+"payPrice:"+payPrice);
            if(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
                //金额对比-成功
                //4.保存订单
                saveOrder(order);
                //5.库存锁定,有异常回滚订单数据
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                List<OrderItemVo> collect = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(collect);
                wareSkuLockVo.setOrderSn(order.getOrderEntity().getOrderSn());
                //库存成功了，但是网络原因超时了，订单回滚，库存不滚。
                //为了保证高并发。库存服务自己回滚。可以发消息给库存服务;
                // 库存服务本身也可以使用自动解锁模式 消息队列
                R r = wareFeignService.orderLockStock(wareSkuLockVo);
                if(r.getCode()==0){
                    responseVo.setCode(0);
                    responseVo.setOrder(order.getOrderEntity());
                    responseVo.setMoney(memberRespVo.getMemberMoney());
                    //TODO 订单创建成功，发送消息给MQ，修改订单状态
                    rabbitTemplate.convertAndSend(OrderConstant.ORDER_EVENT_EXCHANGE,OrderConstant.ORDER_CREATE_ORDER_ROUTING,order.getOrderEntity());
                    return responseVo;
                }else {
                    responseVo.setCode(3);
                    throw new NoStockException();
                }


            }else {
                responseVo.setCode(2);
                throw new VerifyPriceException();
            }

        }
    }

    /**
     * 保存订单数据到数据库
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrderEntity();
        orderEntity.setModifyTime(new Date());
        save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 创建订单
     * @return
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1.生成订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单-构建订单
        OrderEntity orderEntity = buildOrder(orderSn);


        //2,获取到所有的订单项-构建订单项
        List<OrderItemEntity> itemEntities = buidOrderItems(orderSn);

        //3 计算价格,积分等信息
        computePrice(orderEntity,itemEntities);

        orderCreateTo.setOrderEntity(orderEntity);
        orderCreateTo.setOrderItems(itemEntities);
        return orderCreateTo;
    }

    /**
     * 验价-计算价格
     * @param orderEntity
     * @param itemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal integration = new BigDecimal("0");
        BigDecimal growth = new BigDecimal("0");
        for (OrderItemEntity item : itemEntities){
            totalAmount = totalAmount.add(item.getRealAmount());
            integration = integration.add(new BigDecimal(item.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(item.getGiftGrowth().toString()));

        }
        //设置订单金额和应付金额
        orderEntity.setTotalAmount(totalAmount);
        orderEntity.setPayAmount(totalAmount.add(orderEntity.getFreightAmount()));
        //设置订单获取的积分
        orderEntity.setIntegration(integration.intValue());
        orderEntity.setGrowth(growth.intValue());
    }

    /**
     * 构建订单
     * @param orderSn
     */
    private OrderEntity buildOrder(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        orderEntity.setMemberId(memberRespVo.getId());
        //设置收货人和运费信息
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        R r = wareFeignService.getFare(orderSubmitVo.getAddressId());
        FareVo fare = r.getData("fare", new TypeReference<FareVo>() {
        });
        orderEntity.setFreightAmount(fare.getFare());
        orderEntity.setReceiverProvince(fare.getAddress().getProvince());
        orderEntity.setReceiverCity(fare.getAddress().getCity());
        orderEntity.setReceiverRegion(fare.getAddress().getRegion());
        orderEntity.setReceiverDetailAddress(fare.getAddress().getDetailAddress());
        orderEntity.setReceiverPhone(fare.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fare.getAddress().getPostCode());
        orderEntity.setReceiverName(fare.getAddress().getName());

        //设置订单状态
        orderEntity.setStatus(OrderConstant.OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(OrderConstant.autoConfirmDay);
        orderEntity.setDeleteStatus(OrderConstant.noDeleteStatus);
        return orderEntity;

    }

    /**
     * 构建所有订单项数据
     * @return
     */
    private List<OrderItemEntity> buidOrderItems(String orderSn) {
        //2,获取到所有的订单项;
        List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
        if(cartItems!=null&&cartItems.size()>0){
            List<OrderItemEntity> itemEntities = cartItems.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buidOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建某一个订单项数据
     * @param cartItem
     * @return
     */
    private OrderItemEntity buidOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1订单信息
        //2商品的spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuEntity = r.getData("spuEntity", new TypeReference<SpuInfoVo>() {});
        orderItemEntity.setSpuId(spuEntity.getId());
        orderItemEntity.setSpuName(spuEntity.getSpuName());
        orderItemEntity.setSpuBrand(spuEntity.getBrandId().toString());
        orderItemEntity.setCategoryId(spuEntity.getCatalogId());
        //3商品的sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        orderItemEntity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";"));
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        //4优惠信息(忽略)
        //5积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().intValue());
        orderItemEntity.setRealAmount(orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString())));
        return orderItemEntity;
    }


    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order;
    }

    /**
     * 定时关单
     * @param order
     */
    @Override
    public void closeOrder(OrderEntity order) {
        OrderEntity orderEntity= getById(order.getId());
        if(orderEntity.getStatus() == OrderConstant.OrderStatusEnum.CREATE_NEW.getCode()){
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderConstant.OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            //订单关单再给mq发送解锁库存的消息
            try{
                //TODO 保证消息一定会发送出去
                rabbitTemplate.convertAndSend(OrderConstant.ORDER_EVENT_EXCHANGE, OrderConstant.ORDER_RELEASE_OTHER_ROUTING, orderTo);
            }catch (Exception e){
                //TODO 将没发送成功的消息进行重试发送

            }

        }
    }


    /**
     * 获取订单支付的详细信息
     *
     * @param orderSn 订单号
     */
    @Override
    public PayVO getOrderPay(String orderSn) {
        // 查询订单
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        // 查询所有订单项
        OrderItemEntity item = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                .eq("order_sn", orderSn)).get(0);
        PayVO result = new PayVO();
        BigDecimal amount = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);// 总金额
        result.setTotal_amount(amount.toString());
        result.setOut_trade_no(orderSn);
        result.setSubject(item.getSkuName());
        result.setBody(item.getSkuAttrsVals());
        return result;
    }

    /**
     * 处理支付回调
     *
     * @param targetOrderStatus 目标状态
     */
    @Override
    public void handlePayResult(Integer targetOrderStatus, Integer payCode, PaymentInfoEntity paymentInfo) {
        // 保存交易流水信息
        paymentInfoService.save(paymentInfo);

        // 修改订单状态
        if (OrderConstant.OrderStatusEnum.PAYED.getCode().equals(targetOrderStatus)) {
            // 支付成功状态
            String orderSn = paymentInfo.getOrderSn();
            baseMapper.updateOrderStatus(orderSn, targetOrderStatus, payCode);
        }
    }


    /**
     * 分页查询订单列表、订单详情
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        // 获取登录用户
        MemberRespVo member = LoginUserInterceptor.loginUser.get();

        // 查询订单
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                        .eq("member_id", member.getId())
                        .orderByDesc("id"));
        // 查询订单项
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setOrderItemEntityList(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);
       /* List<String> orderSns = page.getRecords().stream().map(order -> order.getOrderSn()).collect(Collectors.toList());
        Map<String, List<OrderItemEntity>> itemMap = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                        .in("order_sn", orderSns))
                .stream().collect(Collectors.groupingBy(OrderItemEntity::getOrderSn));


        // 遍历封装订单项
        page.getRecords().forEach(order -> order.setOrderItemEntityList(itemMap.get(order.getOrderSn())));*/

        return new PageUtils(page);
    }


    @Override
    public void payOrder(PayOrderVo vo) {
        try{


            OrderEntity order = this.getOrderByOrderSn(vo.getOrderSn());
            if(order!=null){
                order.setStatus(OrderConstant.OrderStatusEnum.PAYED.getCode());
                order.setPaymentTime(new Date());
                order.setModifyTime(new Date());
                updateById(order);
                //baseMapper.updateOrderStatusByOrderSn(order.getOrderSn(),OrderConstant.OrderStatusEnum.PAYED.getCode());
                MemberRespVo member = LoginUserInterceptor.loginUser.get();
                BigDecimal money = vo.getMoney();
                BigDecimal payAmount = vo.getPayAmount();
                BigDecimal pay= money.subtract(new BigDecimal("0.01"));
                memberFeignService.updateMemberMoney(pay.toString(), member.getId());

                PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
                paymentInfo.setOrderSn(vo.getOrderSn());
                paymentInfo.setTotalAmount(payAmount);
                paymentInfo.setPaymentStatus("支付成功");
                paymentInfo.setCreateTime(new Date());
                paymentInfoService.save(paymentInfo);
            }



        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
